package tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 429.N叉树的层序遍历
 *
 * @author Api
 * @date 2023/10/21 15:58
 */
public class Code429_SequenceTraversalOfNTree {
    static class Node {
        int val;
        List<Node> children;

        public Node() {
        }

        public Node(int val) {
            this.val = val;
        }

        public Node(int val, List<Node> children) {
            this.val = val;
            this.children = children;
        }
    }
    // N叉树层序遍历
    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> result = new ArrayList<>();
        Queue<Node> queue = new LinkedList<>();
        if (root == null) {
            return result;
        }
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> temp = new ArrayList<>();
            while (size-- > 0) {
                Node node = queue.poll();
                temp.add(node.val);
                if (node.children != null) {
                    for (Node nodeTemp : node.children) {
                        queue.add(nodeTemp);
                    }
                }
            }
            result.add(temp);
        }
        return result;
    }
}
